package com.linghui.videoplus.ipai.activity;

import java.io.File;
import java.io.Serializable;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.linghui.videoplus.ipai.R;
import com.linghui.videoplus.ipai.VideoPlusApplication;
import com.linghui.videoplus.ipai.api.json.JsonAPI;
import com.linghui.videoplus.ipai.bean.VideoBean;
import com.linghui.videoplus.ipai.media.MyVideoView;
import com.linghui.videoplus.ipai.utils.Constants;
import com.linghui.videoplus.ipai.utils.DateUtils;
import com.linghui.videoplus.ipai.utils.ImageUtils;
import com.linghui.videoplus.ipai.utils.StringUtil;

public class MyVideoActivity extends BaseActivity implements OnClickListener,
		OnTouchListener, OnCompletionListener {

	private LinearLayout uploadLayout;
	private LinearLayout shareLayout;
	private LinearLayout deleteLayout;

	private ImageView myPreviewImageView;
	private ImageView myPlayImageView;

	// private ImageView myShareImageView;
	// private ImageView myUplaodImageView;

	private TextView descTextView;
	private TextView uploadTextView;
	
	private EditText modifyDescEV;
	private TextView modifyDescTV;

	private TextView sizeTextView;
	private TextView dateTextView;

	private Display display;
	private VideoBean video;

	private MyVideoView videoView;
	private MyReceiver receiver = null;
	boolean isUpload=false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_my_video);

		menuLayout = (com.linghui.videoplus.ipai.view.MenuLayout) this
				.findViewById(R.id.menuLayout);
		menuLayout.setOnClickListener(this);
		menuLayout.setFocus(R.id.photoLL);
		
		display = this.getWindowManager().getDefaultDisplay();
		int mWidth = display.getWidth() * 4 / 5;
		int mHeight = display.getHeight() / 2;

		video = (VideoBean) getIntent().getSerializableExtra(SERIALIZABLE__KEY);

		shareLayout = (LinearLayout) findViewById(R.id.myShareLL);
		uploadLayout = (LinearLayout) findViewById(R.id.myUploadLL);
		deleteLayout = (LinearLayout) findViewById(R.id.deleteLL);
		shareLayout.setOnTouchListener(this);
		deleteLayout.setOnTouchListener(this);
		uploadLayout.setOnTouchListener(this);

		myPreviewImageView = (ImageView) findViewById(R.id.myPreviewImageView);

		uploadTextView = (TextView) findViewById(R.id.myUplaodTextView);
		descTextView = (TextView) findViewById(R.id.myDescTextView);

		sizeTextView = (TextView) findViewById(R.id.sizeTextView);
		dateTextView = (TextView) findViewById(R.id.dateTextView);

		sizeTextView.setText("视频大小:" + video.getSize());
		dateTextView.setText("拍摄于:"
				+ DateUtils.dateToStr(video.getCreateDate()));
		descTextView.setText(video.getDesc());
		descTextView.setOnTouchListener(this);
		
		myPlayImageView = (ImageView) findViewById(R.id.myPlayImageView);
		myPlayImageView.setOnTouchListener(this);

		if (video.getUploadStatus() == VideoBean.UPLOAD_STATUS_OK) {
			uploadTextView.setText("已经上传");
		}

		videoView = (MyVideoView) findViewById(R.id.myVideoView);
		videoView.setVideoPath(video.getVideoPath());
		videoView.requestFocus();
		videoView.setOnCompletionListener(this);

		Bitmap bitmap = ImageUtils.getLocalBitmap(video.getImageUrl(), mWidth,
				mHeight);
		BitmapDrawable d = new BitmapDrawable(bitmap);
		myPreviewImageView.setImageDrawable(d);
		receiver = new MyReceiver();
	}

	@Override
	protected void onStart() {
		IntentFilter filter = new IntentFilter();
		filter.addAction("android.intent.action.UPLOAD_RECEIVER");
		registerReceiver(receiver, filter);
		super.onStart();
	}

    @Override
    protected void onPause() {
    	super.unregisterReceiver(receiver);
    	super.onPause();
    }
    
    @Override
    protected void onResume() {
    	IntentFilter filter = new IntentFilter();
		filter.addAction("android.intent.action.UPLOAD_RECEIVER");
		registerReceiver(receiver, filter);
    	super.onResume();
    }

	@Override
	public void onCompletion(MediaPlayer mp) {
		myPreviewImageView.setVisibility(View.VISIBLE);
		myPlayImageView.setVisibility(View.VISIBLE);
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (v == myPlayImageView) {
			if (event.getAction() == MotionEvent.ACTION_UP) {
				if (!videoView.isPlaying()) {
					videoView.start();
					myPreviewImageView.setVisibility(View.GONE);
					myPlayImageView.setVisibility(View.GONE);
				}
			}
		} else if (v == deleteLayout) {
			if (event.getAction() == MotionEvent.ACTION_UP) {
				if(isUpload){
					showToast(getResources().getString(R.string.hint_no_delete));
				}else{
					doDeleteVideo();
				}
			}
		} else if (v == uploadLayout) {
			if (video.getUploadStatus() == VideoBean.UPLOAD_STATUS_OK|| isUpload) {
				return false;
			}
			if (event.getAction() == MotionEvent.ACTION_UP) {
				Intent intent = new Intent(this, UploadActivity.class);
				intent.putExtra(FROM_CODE_KEY, REQUEST_CODE_MY_VIDEO);
				intent.putExtra(TO_CODE_KEY, REQUEST_CODE_UPLOAD);
				intent.putExtra(SERIALIZABLE__KEY, video);
				startActivity(intent);
				overridePendingTransition(R.anim.slide_left_in,
						R.anim.slide_left_out);
				this.finish();
			}
		} else if (v == shareLayout) {
			if (event.getAction() == MotionEvent.ACTION_UP) {
				if(isUpload){
					showToast(getResources().getString(R.string.hint_no_share));
					return false;
				}
				Intent shareIntent = new Intent(Intent.ACTION_SEND);
				shareIntent.setType("*/*");
				File f = new File(video.getVideoPath());
				if (f.exists()) {
					shareIntent.putExtra(Intent.EXTRA_SUBJECT, "分享");
					shareIntent.putExtra(Intent.EXTRA_TEXT, video.getDesc());
					shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
					startActivity(Intent.createChooser(shareIntent, "分享"));
				} else {
					showToast("视频不存在!");
				}
			}
		}else if(v == descTextView){
			if (event.getAction() == MotionEvent.ACTION_UP) {
				LayoutInflater layoutInflater = LayoutInflater.from(this);  
		        View myModifyView = layoutInflater.inflate(R.layout.adpter_video_modify, null);  
			    modifyDescEV=(EditText)myModifyView.findViewById(R.id.modifyDescEV);
				modifyDescTV= (TextView)myModifyView.findViewById(R.id.modifyDescTV);
				modifyDescEV.setText(video.getDesc());
				modifyDescEV.addTextChangedListener(mTextWatcher);

				Dialog alertDialog = new AlertDialog.Builder(this).  
                setTitle("修改视频简介").  
                setView(myModifyView).  
                setPositiveButton("修改", new DialogInterface.OnClickListener() {  
                    @Override  
                    public void onClick(DialogInterface dialog, int which) {  
                    	String desc=modifyDescEV.getText().toString();
                    	
                		if (StringUtil.isEmpty(desc)) {
                			showToast("请输入视频描述!");
                			return ;
                		}
                		if (desc.length() > 60) {
                			showToast("视频描述不得超过60个字!");
                			return ;
                		}
                		video.setDesc(desc);
                    	JsonAPI jsonApi=new JsonAPI();
                    	jsonApi.updateMyVideo(MyVideoActivity.this, video);
                    	descTextView.setText(desc);
                    	MyVideoActivity.this.showToast("修改成功!");
                    }  
                }).  
                setNegativeButton("取消", new DialogInterface.OnClickListener() {  
                    @Override  
                    public void onClick(DialogInterface dialog, int which) {  
                    }  
                }).  
                create();  
				alertDialog.show();

			}
		}
		return true;
	}

	@Override
	public void onClick(View v) {
		int vId = v.getId();
		if (vId == R.id.photoLL || vId == R.id.photoImageView) {
			Intent intent = new Intent(this, VideoCascadeActivity.class);
			intent.putExtra(FROM_CODE_KEY, REQUEST_CODE_MY_VIDEO);
			intent.putExtra(TO_CODE_KEY, REQUEST_CODE_VIDEO_CASCADE);
			this.startActivity(intent);
			overridePendingTransition(R.anim.slide_right_in,
					R.anim.slide_right_out);
			this.finish();
		} else if (vId == R.id.cameraLL || vId == R.id.cameraImageView) {
			CameraActivity.launch(this, REQUEST_CODE_DEFAULT,
					REQUEST_CODE_CAMERA);
		} else if (vId == R.id.homeLL || vId == R.id.homeImageView) {
			BrowserActivity.launch(this,
					VideoPlusApplication.getUrlIndex(this),
					REQUEST_CODE_DEFAULT, REQUEST_CODE_DEFAULT);
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// VideoCascadeActivity.launch(this,
			// REQUEST_CODE_MY_VIDEO,REQUEST_CODE_VIDEO_CASCADE);
			Intent intent = new Intent(this, VideoCascadeActivity.class);
			intent.putExtra(FROM_CODE_KEY, REQUEST_CODE_MY_VIDEO);
			intent.putExtra(TO_CODE_KEY, REQUEST_CODE_VIDEO_CASCADE);
			this.startActivity(intent);
			overridePendingTransition(R.anim.slide_right_in,R.anim.slide_right_out);
			this.finish();

		}
		return super.onKeyDown(keyCode, event);
	}
	
	
	/**
	 * 
	 * 删除视频
	 */
	public void doDeleteVideo() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("是否删除视频?");
		builder.setCancelable(false);
		builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				MyVideoActivity.this.showToast("视频删除成功!");
				JsonAPI json = new JsonAPI();
				json.deleteMyVideo(MyVideoActivity.this, video);
				Intent intent = new Intent(MyVideoActivity.this,
						VideoCascadeActivity.class);
				intent.putExtra(FROM_CODE_KEY, REQUEST_CODE_MY_VIDEO);
				intent.putExtra(TO_CODE_KEY, REQUEST_CODE_VIDEO_CASCADE);
				MyVideoActivity.this.startActivity(intent);
				overridePendingTransition(R.anim.slide_right_in,
						R.anim.slide_right_out);
				MyVideoActivity.this.finish();
			}
		});
		builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});

		AlertDialog alert = builder.create();
		alert.show();
	}

	public static void launch(Activity mActivity, int fromCode, int toCode,
			Serializable obj) {
		Intent intent = new Intent(mActivity, MyVideoActivity.class);
		intent.putExtra(FROM_CODE_KEY, fromCode);
		intent.putExtra(TO_CODE_KEY, toCode);
		intent.putExtra(SERIALIZABLE__KEY, obj);
		mActivity.startActivity(intent);
		mActivity.finish();
	}

	/**
	 * 广播接收器
	 * 
	 * @author user
	 */
	private class MyReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			Message msg = handler.obtainMessage();
			Bundle mBundle = new Bundle();
			int msg_what = intent.getIntExtra("MSG_WHAT",
					Constants.EXTRA_UPLOAD_STATUS_FAIL);
			if (msg_what == 1) {
				int status = intent.getIntExtra(Constants.EXTRA_UPLOAD_KEY,
						Constants.EXTRA_UPLOAD_STATUS_FAIL);
				mBundle.putInt(Constants.EXTRA_UPLOAD_KEY, status);

			} else if (msg_what == 2) {
				int progress = intent.getIntExtra("PROGRESS", 0);
				mBundle.putInt("PROGRESS", progress);
			}
			msg.what = msg_what;
			msg.setData(mBundle);
			handler.sendMessage(msg);

		}
	};

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			Bundle mBundle = msg.getData();
			switch (msg.what) {
			case 1: // 进度条消息
				int status = mBundle.getInt(Constants.EXTRA_UPLOAD_KEY);
				if (status == Constants.EXTRA_UPLOAD_STATUS_OK) {
					uploadTextView.setText("上传成功");
					MyVideoActivity.this.showToast("已上传至看看新闻网!");
					isUpload=false;
				}
				break;
			case 2:
				int progress = mBundle.getInt("PROGRESS");
				isUpload=true;
				uploadTextView.setText(progress + "%");
			}
		}
	};
	private TextWatcher mTextWatcher = new TextWatcher() {
		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

			String str = s.toString();
			String desc=null;
			if (str.length() > 60) {
				desc = str.substring(0, 60);
				modifyDescEV.setText(desc);
			} else {
				desc = str;
			}
			modifyDescTV.setText("剩余" + (60 - desc.length()) + "字");
		}
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void afterTextChanged(Editable s) {

		}
	};
}
